# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(plyr)
library(gridExtra)
library(scales)
library(egg)
library(VennDiagram)
library(optparse)
library(tidyverse)
library(magrittr)

createWhenNoExist <- function(f){
    ! dir.exists(f) && dir.create(f)
}

option_list <- list(
)
opt <- parse_args(OptionParser(option_list = option_list))

parent <- paste0("./")
createWhenNoExist(parent)

workspacePath<-"../../"

dir <- str_c(workspacePath)
dirs <- list.dirs(dir, recursive = F) %>%
keep(~ str_detect(.x, "_vs_"))
treats <- basename(dirs)

tbf <- tibble()

for (treat in treats) {
    subDir <- str_c(workspacePath, treat, "/cor/01")
    fileParent <- list.dirs(subDir, recursive = F) %>%
    keep(~ str_detect(.x, "_and_")) %>%
        head(1)
   filePath<-str_c(fileParent,"/Network_Nodes_for_Cytoscape.csv")
    data <- read_csv(filePath) %>%
        select("Node") %>%
        rename_at(vars(c("Node")), function(x){
            c(treat)
        })

    if (nrow(data) > 0) {
        data <- data %>%
        mutate(id = 1 : n())
    }else{
        data <- data %>%
        add_column(id = NA)
    }

    if (nrow(tbf) == 0) {
        tbf <- data
    }else {
        tbf <- tbf %>%
        full_join(data, by = "id")
    }
}

columnNames <-treats
outData <- tbf
size<-length(columnNames)

if(length(columnNames)>1){
    for(i in size:2){
        cn <- combn(columnNames, i)
        for (i in 1 : ncol(cn)) {
            row <- cn[, i]
            columnName <-str_c(row, collapse = " & ")
            outData <- outData %>%
            mutate(!!columnName := {
                values <- row %>%
                map(function(t){
                    get(t)
                })
                x <- Reduce(intersect, values)
                x[1 : n()]
            })
        }
    }
}

if(length(columnNames)<=5){
  for (name in columnNames) {
    newName <- str_c(name, " only")
    outData <- outData %>%
      mutate(!!newName:= {
        otherNames <- columnNames %>%
          discard(~ .x %in% c(name))
        values <- c(name, otherNames) %>%
          map(function(t){
            get(t)
          })
        x <- Reduce(setdiff, values)
        x[1 : n()]
      })
  }
}

outData <- outData %>%
    mutate_all(function(x){
        replace_na(x, "")
    }) %>%
    select(- c(1 : (size+1)))
outData
write_csv(outData, "Intra_Correlation_Venn_Data.csv")





